<script setup lang="ts">
import { reactive, watch, onMounted } from 'vue'
import _ from 'lodash'

const props = defineProps({
  width: {
    type: String,
    default: () => 'w-full'
  },
  titles: {
    type: Array<String>,
    default: () => []
  },
  leftData: {
    type: Array,
    default: () => [] as any
  },
  rightData: {
    type: Array,
    default: () => [] as any
  },
  leftDefault: {
    type: Array,
    default: () => [] as any
  },
  rightDefault: {
    type: Array,
    default: () => [] as any
  },
  option: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits(['change'])

const states = reactive({
  lData: _.cloneDeepWith(props.leftData),
  rData: [] as any,
  lDefault: [] as any,
  rDefault: [] as any
})

const initRightData = () => {
  states.rData = []
  _(props.rightData).forEach((item: any) => {
    states.rData.push(item[props.option?.key])
  })
}

const initLeftDefault = () => {
  states.lDefault = []
  _(props.leftDefault).forEach((item: any) => {
    states.lDefault.push(item[props.option?.key])
  })
}

const initRightDefault = () => {
  states.rDefault = []
  _(props.rightDefault).forEach((item: any) => {
    states.rDefault.push(item[props.option?.key])
  })
}

const handleChange = (value: any) => {
  const arr: any = []

  if (value.length > 0) {
    _(states.lData).forEach((item: any) => {
      if (_.indexOf(value, item[props.option?.key]) !== -1) {
        arr.push(item)
      }
    })
  }

  emit('change', arr)
}

onMounted(() => {
  initRightData()
  initLeftDefault()
  initRightDefault()
})

watch(
  () => props.leftData,
  (val) => {
    states.lData = _.cloneDeepWith(val)
  }
)

watch(
  () => props.rightData,
  () => {
    initRightData()
  }
)
</script>

<template>
  <div :class="props.width">
    <el-transfer
      v-model="states.rData"
      filterable
      filter-placeholder="State Abbreviations"
      :titles="props.titles"
      :data="states.lData"
      :left-default-checked="states.lDefault"
      :right-default-checked="states.rDefault"
      :props="{
        key: props.option?.key,
        label: props.option?.label
      }"
      @change="handleChange"
    />
  </div>
</template>

<style lang="scss" scoped></style>
